<?php

namespace App\Models;

use App\Helpers\RequestCriteria;
use App\Helpers\BaseModel;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable  implements JWTSubject
{
    use HasApiTokens, HasFactory, Notifiable, HasRoles, RequestCriteria, BaseModel;
    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'mobile',
        'remarks'
    ];
    protected $guarded = [];
    protected $guard_name = 'api';

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'password' => 'hashed',
        'email_verified_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s',
        'created_at' => 'datetime:Y-m-d H:i:s',
    ];
    /**
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    public function enterprises()
    {
        return $this->belongsToMany(Enterprise::Class, 'user_has_enterprises');
    }

    public function assignEnterprise($enterprise)
    {
        $enterprise = Enterprise::where('name', $enterprise)->first();
        $model = $this->getModel();
        if ($model->exists) {
            $this->enterprises()->sync($enterprise, false);
            $model->load('enterprises');
        } else {
            $class = \get_class($model);
            $class::saved(
                function ($object) use ($enterprise, $model) {
                    if ($model->getKey() != $object->getKey()) {
                        return;
                    }
                    $model->enterprise()->sync($enterprise, false);
                    $model->load('enterprises');
                }
            );
        }
        return $this;
    }
    
    public function openapi()
    {
        return $this->hasMany(OpenAPI::Class);
    }

    public function eSStations()
    {
        return $this->morphedByMany(ESStation::class, 'manage', 'user_managements')->withTimestamps();
    }
    // public function enterprise()
    // {
    //     return $this->morphToMany(Enterprise::class, 'manage', 'user_managements');
    // }
}
